<?php
 /******************************************************************************
 *   GunCMS is an avid supporter of open source software. This is the appropriate 
 *   option if you are creating an open source application with a license 
 *   compatible with the GNU GPL license v3.
 *   For details http://www.gnu.org/licenses/gpl.html
 *   DO NOT USE FOR COMMERCIAL WITHOUT PERMISSION
 *
 * GunCMS Version 1.0.3
 * Copyright(c) 2009-2010, T & L GdbR
 * info@guncms.de
 * 
 * http://www.guncms.de
 ********************************************************************************/
class BgcmsUser extends BgcmsProcess{
	var $db;
 	var $smarty;	
	public function __construct($db, $smarty) {
		$this->db = $db;
		$this->smarty = $smarty;
	}
		
	public function __destruct() {
		//
	}
	
	public function forgotpass(){
		$msg = "";
		if(isset($_POST['email']) && $_POST['email'] != ""){
			$msg = "";
			$email = $_POST['email'];
			$check = BgcmsUserBean::check_email_address($email);
			if($check == false){
				$msg .= "Invalid email address.";
			}else{
				$exists = BgcmsUserBean::ExistsByEmail($this->db,$email);
				if($exists == "")
				{
					$msg .= "This email address not exists.";
				}
			}
		}else{
			$msg .= "Invalid email address.";
		}
		if($msg == ""){
			$time = time();
			$to = $email;
			$get_code = md5($time); // tao 6 so ngau nhien
			$pass= substr($get_code, 0, 10);
			$passcrypt = md5($pass);
			BgcmsUserBean::updatePassword($this->db, $email, $passcrypt);
			
			$type = array('ID' => 0);
			$host = $_SERVER['HTTP_HOST'].FOLDER_HOST;
			$code = md5($to);
			$from = FROMMAIL;
			$fromname = "T & L Tec GdbR";
			$subject = "GuN CMS Admin Passwort ";
			$message = 	"Hallo,<br /><br />" .
						"Login: ".$exists->user_name."<br />" .
						"Passwort: $pass<br /><br /><br />" .
						"Gruss,<br /><br />" . 
						"T & L Tec GdbR<br />" .
						"Plattlinger Strasse 5a<br />" .
						"93055 Regensburg<br />" .
						"Email: info@guncms.de<br />" .
						"Germany";
			$header = "Content-type: text/html\r\nFrom: $from\r\nReply-to: $from";
			bgcmsEmail::send_mail($to, $message, $subject, $from, $fromname, false);
			$msg = "send pass successful";
			setcookie("message", $msg,time()+5);
			header("Location: ./");
		}else{
			setcookie("message", $msg,time()+5);
			header("Location: ./?page=forgotpass");
		}		
		
	}
	
	public function show_user_list(){
		//$users = BgcmsUserBean::get_all_user($this->db);
		
		$users = array();
		$countuser = BgcmsUserBean::count_all_user($this->db);
		$users['data'] = BgcmsUserBean::get_all_user_paging($this->db,ADMINPAGING,"list");
		$result = BgcmsPaging::do_paging($countuser,$users, ADMINPAGING, "?module=BgcmsUser&sub1=UserList","list");
		
		$this->smarty->assign("USERS", $result);
		//$this->Run();	
		$this->smarty->display('BgcmsUser/index.tpl');
	}
	
	public function process(){
		$sub1 = "UserList";
		if(isset($_GET['sub1'])) {
			$sub1 = $_GET['sub1'];
		}
		if($sub1 == "") $sub1 = "UserList";
		
		if($sub1 == "UserList" || $sub1 == "edituser") {
			$this->process_user($sub1);
		} elseif ($sub1 == "UserPost") {
			$this->process_user_post($sub1);
		}
		$this->show_user_list();
	}
	
	public function process_user($sub1) {
		if(isset($_GET['mess'])) {
			$msg = "";
			switch($_GET['mess']) {
				case 1:
					$msg = _("User updated.");
					break;
				case 2:
					$msg = _("User not updated. Maybe you have not change anything.");
					break;
				case 3:
					$msg = _("User has been added");
					break;		
			}	
			$this->smarty->assign("resp_message", $msg);
		}
		if(isset($_POST['act'])) {
			$act = $_POST['act'];
			if($act == "adduser") {
				$this->create_user();
			} elseif ($act == "edituser") {
				$this->edit_user();
			} elseif($act == "deluser") {
				$this->delete_user();
			}
		} else {
			if($sub1 == "edituser") {
				$id = @$_GET['id'];
				$user = BgcmsUserBean::get_user_by_id($this->db, $id);
				$this->smarty->assign("THEUSER", $user);
				//$this->smarty->display('BgcmsUser/index.tpl');
			}
			//$this->show_user_list();
		}
	}
	
	function process_user_post($sub1) {
		$id = @$_SESSION['user_id']; 
		if(!isset($_POST['act'])) {
			$page = BgcmsPageBean::get_all_page_by_condition($this->db, "page_author=" . $id);
			$this->smarty->assign("PAGES", $page);
		} else {
			$act = $_POST["act"];
			if($act == "browse_cat") {
				$this->smarty->assign("COMMENT", 
					_("Results for browse page by category"));
				$pages = BgcmsPageBean::get_all_page_by_cat($this->db, $_POST['cat'], $id);
			} elseif($act == "browse_month") {
				$this->smarty->assign("COMMENT", 
					_("Results for browse page by month"));
				$this->smarty->assign("SELMONTH", $_POST['Date_Month']);
				$pages = BgcmsPageBean::get_all_page_by_condition($this->db, 
						"page_author=" . $id . 
						" AND MONTH(page_date) = " . $_POST['Date_Month']);
			}
			$pages = array();
			$countpage =  BgcmsPageBean::count_all_page($this->db, "","",$_SESSION["LC_ALL"]);
			$pages['data'] = BgcmsPageBean::get_all_page_paging($this->db, "","",$_SESSION["LC_ALL"],ADMINPAGING,"list");
			$result = BgcmsPaging::do_paging($countpage,$pages, ADMINPAGING, "?module=BgcmsUser&sub1=UserPost","list");
			
			$this->smarty->assign("PAGES", $result);
		}
		
		//Get all category for search
		$catList = BgcmsCategoryBean::get_all_category($this->db, null);
		$this->smarty->assign("CATS", $catList);
		//$this->smarty->display('BgcmsUser/index.tpl');
	}
	public function create_user() {
		$msg = BgcmsUser::validate_user($this->db);
		$arr = array("code" => -1, "message" => _("Could not add user."));
		if($msg == "") {
			$id = BgcmsUserBean::save_user($this->db, $_POST);
			if($id >=0 ) {
				$arr = array("code" => 0, "message" => _("New user has been added."), "user_id" => $id);
				$arr['linkactive'] = "?module=BgcmsUser&sub1=UserList&mess=3";		
				
			}
		} else {
			$arr = array("code" => -1, "message" => $msg);
		}
		echo array2json($arr);
				
	}
	
	public function edit_user() {
		if(isset( $_POST['user_id'])) {
			$msgId = 2;
			$msg = $this->validate_user($this->db);
			if($msg == "") {
				if($_POST['user_id'] == '1')
					$style = 'myprofile';
				$res = BgcmsUserBean::update_user($this->db, $_POST,$style);
				$msgId = 1;
				$arr = array('ID' => 0,'msg' => 1);
				$arr['linkactive'] = "?module=BgcmsUser&sub1=UserList&mess=1";	
			} else {
				$arr = array('ID' => -1, 
							 'message' => $msg);
			}
			echo array2json($arr);
		}
	}
	
	public function delete_user() {
		$arr = array('code' => 0, 'message' => "");
		$id = @$_POST['id'];
		$res = BgcmsUserBean::delete_user_by_id($this->db, $id);
		if($res == true) {
			$arr['code'] = 0;
			$arr['message'] = sprintf(_("User <u>%s</u> has been deleted."), $id);
		} else {
			$arr['code'] = -1;
			$arr['message'] = sprintf(_("Could not delte user <u>%s</u>."), $id);
		}
		echo array2json($arr);
	}
	
    public static function validate_user($db) {
    	$msg = "";
    	if($_POST['user_name'] == "") {
			$msg = "Please type the Username.";
		}
		if(!isset($_POST['user_id'])) {
			if(BgcmsUserBean::existed_user_by_name($db, $_POST['user_name'])) {
				if($msg != "") $msg .= "<br />";
				$msg .= "Username already registered.";
			}
		}
		if($_POST['user_email'] == "") {
			if($msg != "") $msg .= "<br />";
			$msg .= "Please type an e-mail address.";
		}
		if($_POST['user_email'] != "") {
			$flag = BgcmsUser::check_email_address($_POST['user_email']);
			if($flag == false) {
				if($msg != "") $msg .= "<br />";
				$msg .= "Invalid email address.";
			}
		}
		if($_POST['user_password'] == "") {
			if($msg != "") $msg .= "<br />";
			$msg .= "Password fields can not be empty.";
		}
		if($_POST['user_password'] != "" && strlen($_POST['user_password']) < 6) {
			if($msg != "") $msg .= "<br />";
			$msg .= "Your password must contain at least 6 characters.";
		}
		if($_POST['user_password'] != $_POST['user_password2']) {
			if($msg != "") $msg .= "<br />";
			$msg .= "Please type the same password in the two password fields.";
		}
		return $msg;
    }
    
	function check_email_address($email) 
	{
    	// First, we check that there's one @ symbol, and that the lengths are right
    	if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) 
    	{
    	// Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
    	return false;
    	}
    	// Split it into sections to make life easier
    	$email_array = explode("@", $email);
    	$local_array = explode(".", $email_array[0]);
   		for ($i = 0; $i < sizeof($local_array); $i++) 
   		{
   			if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) 
   			{
   			return false;
   			}
   		}
   		if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1]))  // Check if domain is IP. If not, it should be valid domain name
   		{
   			$domain_array = explode(".", $email_array[1]);
   			if (sizeof($domain_array) < 2) 
   			{
   			return false; // Not enough parts to domain
   			}
   			for ($i = 0; $i < sizeof($domain_array); $i++) 
   			{
   				if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) 
   				{
   				return false;
   				}
   			}
   		}
   		return true;
	}
}
?>